Retrieving a Scalar Value

You can use the ExecuteScalar method of the Command object to return a single value, such as a sum or a count, from the database. The ExecuteScalar method returns the value of the first column of the first row of the result set.

The following code example, which requires the emp table (see "Sample Tables for Sybase"), shows how to retrieve the count of a specified group:

// Retrieve the number of employees who make more than $50000 
// from the emp table 
// Open connection to SequeLink Server on Sybase database 
SequeLinkConnection  Conn; 
Conn = new SequeLinkConnection("host=bowhead;port=19996;User ID=test01; 
                               Password=test01"); 
Conn.Open(); 
// Make a command object  
SequeLinkCommand  salCmd = new SequeLinkCommand("SELECT COUNT(sal) FROM emp 
                                                 WHERE sal>'50000'",Conn); 
try 
{ 
    int count = (int)salCmd.ExecuteScalar(); 
} 
catch (Exception ex)  
{ 
    // Display any exceptions in a messagebox 
    MessageBox.Show (ex.Message); 
} 
//  Close the connection 
Conn.Close();